﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;
using System.Collections;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
namespace VSM
{
    public partial class TechnicalDocSetup : System.Web.UI.Page
    {
        private static GeneralFunctions GF = null;
        private static string dbType;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                          || Session[Utils.AppConstants.Password] == null
                          || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            
            if (!IsPostBack)
            {
                Services sv = new Services();
                dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataSet dsModel = sv.ExecuteQuery("VSM", "Select -1 as ModelCode, 'Choose Model' as ModelName  UNION ALL select ModelCode, ModelName from U_Model");
                ddl_Model.DataSource = dsModel.Tables[0];
                ddl_Model.DataTextField = "ModelName";
                ddl_Model.DataValueField = "ModelCode";
                ddl_Model.DataBind();
            }
        }

        private string FormatDate(string dateIn) {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");
            
        }


        private void loadDetail()
        {
            string ModelCode = ddl_Model.SelectedValue.ToString();
            if (ModelCode != "-1")
            {

                string sql = "select ROW_NUMBER() OVER (ORDER BY BulletinID) AS No, BulletinID, BulletinName, ModelCode, FilePath from U_Bulletin where ModelCode= " + ModelCode;

                Services sv = new Services();
                Session["Bulletin"] = sv.ExecuteQuery("VSM", sql).Tables[0];
                grvPO.DataSource = (DataTable)Session["Bulletin"];
                grvPO.DataBind();
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Please choose a model.');", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            if (tblData.Rows.Count > 0)
            {
                DataRow dr = tblData.Rows[0];
                //txtDealerCode.Text = dr["CardCode"].ToString();
                //txtDealerName.Text = dr["CardName"].ToString();
                //txtAddress.Text = dr["Address"].ToString();
                //txtTaxCode.Text = dr["LicTradNum"].ToString();
                //txtTel1.Text = dr["Phone1"].ToString();
                //txtTel2.Text = dr["Phone2"].ToString();
                //txtMobilePhone.Text = dr["Cellular"].ToString();
                //txtEmail.Text = dr["E_mail"].ToString();
                //txtFax.Text = dr["Fax"].ToString();
            }
           
        }

        protected void btn_AddMultiItems_Click(object sender, EventArgs e)
        {
            //BulletinID, BulletinName, ModelCode, FilePath
            DataTable dtTmp = (DataTable)Session["Bulletin"];
            DataRow dr = dtTmp.NewRow();
            dr["No"] = dtTmp.Rows.Count + 1;
            dr["BulletinID"] = -1;
            dr["ModelCode"] = ddl_Model.SelectedValue.ToString();

            dr["BulletinName"] = "";
            dr["FilePath"] = "";
           
            dtTmp.Rows.Add(dr);
            this.grvPO.DataSource = dtTmp;
            this.grvPO.DataBind();
            Session["Bulletin"] = dtTmp;
        }

        //RUKOWEN ADDED
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    GridViewRow myRow = e.Row;
            //    Label lblNo = myRow.FindControl("lblNo") as Label;
            //    lblNo.Text = (myRow.RowIndex + 1).ToString();
            //    //if (this.hdnStatus.Value == "C")
            //    //{
            //    //    TextBox txtQuantity = myRow.FindControl("txtOrderQuantity") as TextBox;
            //    //    txtQuantity.Enabled = false;
            //    //}
            //}
        }

        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvPO.PageIndex = e.NewPageIndex;
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            BindData(tblPOR1);
        }

        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            /*
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                int index = 0;
                TextBox ddl1 = e.Row.FindControl("txtOrderQuantity") as TextBox;
                ddl1.Attributes.Add("onfocus", "JavaScript:document.getElementById('" + ddl1.ClientID + "').select();");
                if (ViewState["rowindex"] != null && Session["POTable"] != null)
                {
                    index = Convert.ToInt32(ViewState["rowindex"].ToString());
                    int rowCount = ((DataTable)Session["POTable"]).Rows.Count;
                    if ((index + 1) <= this.grvPO.Rows.Count)
                    {
                        if (e.Row.RowIndex == index + 1)
                        {
                            ddl1.Focus();
                            //ScriptManager.GetCurrent(this).SetFocus(ddl1.ClientID);
                        }
                    }
                }
            }
             * */
        }

        private void saveGrid()
        {
            DataTable dtTmp = (DataTable)Session["Bulletin"];
            dtTmp.Rows.Clear();

            foreach (GridViewRow row in grvPO.Rows)
            {
                DataRow newRow = dtTmp.NewRow();
                newRow["No"] = ((Label)row.FindControl("lbl_No")).Text;
                newRow["BulletinID"] = ((Label)row.FindControl("lbl_BulletinID")).Text;
                newRow["ModelCode"] = ((Label)row.FindControl("lbl_ModelCode")).Text;
                newRow["BulletinName"] = ((TextBox)row.FindControl("txt_BulletinName")).Text;

                FileUpload fu = ((FileUpload)row.FindControl("fu_File"));
                
                Label lb_fPath =  ((Label)row.FindControl("lbl_FilePath"));

                if (lb_fPath.Text == "")
                    newRow["FilePath"] = fu.FileName;
                else
                    newRow["FilePath"] = lb_fPath.Text;

                dtTmp.Rows.Add(newRow);
            }
            Session["Bulletin"] = dtTmp;
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                saveGrid();
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lbl_No");
                int rowNo = Int32.Parse(lblNo.Text);
                DataTable dtTmp = (DataTable)Session["Bulletin"];
                Services sv = new Services();
                foreach (DataRow dr in dtTmp.Rows)
                {
                    if (rowNo == Int32.Parse(dr["No"].ToString()))
                    {
                        string DetID = dr["BulletinID"].ToString();
                        if (DetID != "-1")
                        {
                            DataSet dsDel = new DataSet();
                            DataTable dtDel = new DataTable();
                            dtDel.Columns.Add("BulletinID");
                            DataRow drDel = dtDel.NewRow();
                            drDel["BulletinID"] = DetID;

                            dtDel.Rows.Add(drDel);
                            dsDel.Tables.Add(dtDel);
                            sv.DeleteBulletin("VSM", dsDel);
                        }
                        dr.Delete();
                        break;
                    }
                }
                //reset number
                dtTmp.AcceptChanges();
                int index = 0;
                foreach (DataRow dr in dtTmp.Rows)
                    dr["No"] = ++index;

                Session["Bulletin"] = dtTmp;
                grvPO.DataSource = dtTmp;
                grvPO.DataBind();
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Delete] Operation complete.');", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Delete] Operation incomplete.');", true);
                //this.lblError.Text = ex.Message;
                //this.lblError.Visible = true;
            }
              
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            uploadFile();
            saveGrid();
            
            DataSet dsDetail = new DataSet();
            DataTable dtDetail = new DataTable();
            dtDetail.Columns.Add("BulletinID");
            dtDetail.Columns.Add("ModelCode");
            dtDetail.Columns.Add("BulletinName");
            dtDetail.Columns.Add("FilePath");

            Services svc = new Services();
            DataTable dtTmp = (DataTable)Session["Bulletin"];
            foreach (DataRow drDetail in dtTmp.Rows)
            {
                dsDetail.Tables.Clear();
                DataRow toAdd = dtDetail.NewRow();

                toAdd["BulletinID"] = drDetail["BulletinID"];
                toAdd["ModelCode"] = drDetail["ModelCode"];

                toAdd["BulletinName"] = drDetail["BulletinName"];
                toAdd["FilePath"] = drDetail["FilePath"];
               
                dtDetail.Rows.Clear();
                dtDetail.Rows.Add(toAdd);
                dsDetail.Tables.Add(dtDetail);


                if (drDetail["BulletinID"].ToString() == "-1")
                    svc.InsertBulletin("VSM", dsDetail);
                else
                    svc.UpdateBulletin("VSM", dsDetail);

            }
            loadDetail();
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Update] Operation complete.');", true);
        }

        protected void btn_Load_Click(object sender, EventArgs e)
        {
            loadDetail();
        }

        private void uploadFile() {
            foreach (GridViewRow row in grvPO.Rows)
            {
                FileUpload fu = ((FileUpload)row.FindControl("fu_File"));
                if (fu.HasFile) {
                    string filePath = Server.MapPath("Technical");
                    fu.SaveAs(Path.Combine(filePath, fu.FileName));

                    //fu.PostedFile.ContentLength
                }
            }
        }
        
    }

}